import { message } from 'antd';
import dayjs from 'dayjs';
import { TimeScheme } from '../types/timeStrategy';

// 辅助转换函数：获取峰谷类型
export const getPeakValleyType = (timeType: string): number => {
  const peakValleyMap: { [key: string]: number } = {
    尖: 1,
    峰: 2,
    平: 3,
    谷: 4,
  };
  return peakValleyMap[timeType] || 1;
};

// 辅助转换函数：获取充放电控制类型
export const getCtrlType = (intl: any, chargeType: string): number => {
  const ctrlTypeMap: { [key: string]: number } = {
    [intl.formatMessage({ id: 'strategyAction.chargeDischargeStrategy.noChargeDischarge' })]: 2,
    [intl.formatMessage({ id: 'strategyAction.chargeDischargeStrategy.chargeAndDischarge' })]: 1,
    [intl.formatMessage({ id: 'strategyAction.chargeDischargeStrategy.onlyCharge' })]: 3,
    [intl.formatMessage({ id: 'strategyAction.chargeDischargeStrategy.onlyDischarge' })]: 4,
  };
  return ctrlTypeMap[chargeType] || 2;
};

// 验证策略名称是否重复
export const validateStrategyName = (
  name: string,
  currentSchemes: TimeScheme[],
  currentId?: number,
): boolean => {
  const isDuplicate = currentSchemes.some(
    (scheme) => scheme.schemeName === name && scheme.id !== currentId,
  );

  return !isDuplicate;
};

// 获取下个月第一天
export const getNextMonthFirstDay = (currentMonth: number) => {
  return {
    month: currentMonth === 12 ? 1 : currentMonth + 1,
    day: 1,
  };
};

// 验证日期顺序
export const validateDateOrder = (
  newDate: dayjs.Dayjs,
  currentIndex: number,
  strategies: any[],
  intl: any,
): boolean => {
  // 如果是最后一条记录（次月第一天），不需要验证
  if (currentIndex === strategies.length - 1) {
    return true;
  }

  const day = newDate.date();
  const prevStrategy = currentIndex > 0 ? strategies[currentIndex - 1] : null;
  const nextStrategy = strategies[currentIndex + 1];

  // 检查日期顺序
  if (prevStrategy && nextStrategy) {
    // 如果下一个策略是最后一条（次月第一天），只需要检查与前一个策略的关系
    if (nextStrategy.isLastDay) {
      if (day <= prevStrategy.day) {
        message.error(
          intl.formatMessage({ id: 'strategyAction.error.dateMustBeGreaterThanPreviousDate' }),
        );
        return false;
      }
    } else {
      // 如果时间段的日，必须严格按照时间顺序
      if (day <= prevStrategy.day || day >= nextStrategy.day) {
        message.error(
          intl.formatMessage({
            id: 'strategyAction.error.dateMustBeStrictlyBetweenPreviousAndNextDate',
          }),
        );
        return false;
      }
    }
  } else if (prevStrategy) {
    // 如果是最后一个普通日期，必须大于前一个日期
    if (day <= prevStrategy.day) {
      message.error(
        intl.formatMessage({ id: 'strategyAction.error.dateMustBeGreaterThanPreviousDate' }),
      );
      return false;
    }
  } else if (nextStrategy) {
    // 如果是第一个日期，必须小于后一个日期
    // 如果后一个是最后一天（次月第一天），则不需要比较
    if (!nextStrategy.isLastDay && day >= nextStrategy.day) {
      message.error(intl.formatMessage({ id: 'strategyAction.error.dateMustBeLessThanNextDate' }));
      return false;
    }
  }

  return true;
};

// 计算中间日期
export const calculateMiddleDay = (strategies: any[]) => {
  if (strategies.length < 1) return 15; // 默认中间日期

  // 获取最后一个非次月第一天的策略
  const lastNormalStrategy = strategies[strategies.length - 1];
  const firstStrategy = strategies[0];

  // 计算中间日期
  const firstDay = firstStrategy.day;
  const lastDay = lastNormalStrategy.day;

  return Math.floor((firstDay + lastDay) / 2);
};

// 排序日期策略
export const sortDateStrategies = (strategies: any[]) => {
  // 分离最后一天（次月第一天）和其他策略
  const lastDayStrategy = strategies.find((s) => s.isLastDay);
  const normalStrategies = strategies.filter((s) => !s.isLastDay);

  // 对普通策略进行排序
  const sortedNormalStrategies = [...normalStrategies].sort((a, b) => {
    if (a.month === b.month) {
      return a.day - b.day;
    }
    return a.month - b.month;
  });

  // 如果有最后一天策略，添加到末尾
  return lastDayStrategy ? [...sortedNormalStrategies, lastDayStrategy] : sortedNormalStrategies;
};

// 转换时间控制到表单值
export const timeCtrlToFormValues = (intl: any, timeCtrl: any) => {
  return {
    startTime: timeCtrl.startTime,
    chargeType:
      timeCtrl.ctrlType === 0 || timeCtrl.ctrlType === 2
        ? intl.formatMessage({ id: 'strategyAction.chargeDischargeStrategy.noChargeDischarge' })
        : timeCtrl.ctrlType === 1
        ? intl.formatMessage({
            id: 'strategyAction.chargeDischargeStrategy.chargeAndDischarge',
          })
        : timeCtrl.ctrlType === 3
        ? intl.formatMessage({ id: 'strategyAction.chargeDischargeStrategy.onlyCharge' })
        : timeCtrl.ctrlType === 4
        ? intl.formatMessage({ id: 'strategyAction.chargeDischargeStrategy.onlyDischarge' })
        : intl.formatMessage({
            id: 'strategyAction.chargeDischargeStrategy.noChargeDischarge',
          }),
    timeType:
      timeCtrl.peakValleyType === 1
        ? intl.formatMessage({ id: 'strategyAction.electricityPrices.highPeak' })
        : timeCtrl.peakValleyType === 2
        ? intl.formatMessage({ id: 'strategyAction.electricityPrices.peak' })
        : timeCtrl.peakValleyType === 3
        ? intl.formatMessage({ id: 'strategyAction.electricityPrices.midPeak' })
        : intl.formatMessage({ id: 'strategyAction.electricityPrices.offPeak' }),
    socUpper: timeCtrl.socUpperLimit,
    socLower: timeCtrl.socLowLimit,
    targetPower: timeCtrl.targetPower,
  };
};
